package cn.stylefeng.guns.modular.demo.excel.listener.aslikang.shenji;

import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.entity.GaiaBatchInfo;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.SaleStock;
import cn.stylefeng.guns.dao.service.IGaiaBatchInfoService;
import cn.stylefeng.guns.modular.demo.enums.SaleStockTypeEnum;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.WholesaleExcelVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.shenji.PeisongExcelVo;
import cn.stylefeng.guns.modular.demo.service.TestBizService;
import cn.stylefeng.guns.util.RebateDateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 阿斯利康采购数据
 */
@Slf4j
public class SalePeisongListener implements ReadListener<PeisongExcelVo> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<SaleStock> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<String> keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ISaleStockService saleStockService;

    private List<String> errorList;
    private IGoodsService goodsService;

    private TestBizService testBizService;
    private IGaiaBatchInfoService gaiaBatchInfoService;
    private String tag;

    public SalePeisongListener(ISaleStockService saleStockService, List<String> errorList, IGoodsService goodsService, TestBizService testBizService, IGaiaBatchInfoService gaiaBatchInfoService, String tag) {
        this.saleStockService = saleStockService;
        this.errorList = errorList;
        this.goodsService = goodsService;
        this.testBizService = testBizService;
        this.gaiaBatchInfoService = gaiaBatchInfoService;
        this.tag = tag;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(PeisongExcelVo data, AnalysisContext context) {
        //w0crdxdq50ss
        log.info("解析到一条数据:{}", JSON.toJSONString(data));

//        LocalDateTime dateTime = LocalDateTime.parse(data.getDate(), RebateDateUtil.formatter);
//        long time = dateTime.toInstant(ZoneOffset.UTC).toEpochMilli();

        LocalDate dateTime = LocalDate.parse(data.getDate(), RebateDateUtil.formatter);
        long epochSecond = dateTime.toEpochSecond(LocalTime.now(), ZoneOffset.UTC);
        String storeCode = data.getStoreCode();
        String productCode = data.getProductCode();
        //批发销售数量
        //批号
        String batch = data.getBatch();
        Integer num = data.getNum();

        List<GaiaBatchInfo> gaiaBatchInfoList = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery()
                .eq(GaiaBatchInfo::getBatBatch, batch))
//                .eq(GaiaBatchInfo::getBatProCode, productCode))
                ;
        if (CollectionUtils.isEmpty(gaiaBatchInfoList)) {
            log.error("批号数据有问题,批号:{}", batch);
            return;
        }
        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoList.get(0);
        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, productCode));
        if (Objects.isNull(goods)) {
            log.error("商品数据有问题,商品编码:{}", productCode);
        }
        testBizService.generateSingleSaleData(num, productCode, storeCode, gaiaBatchInfo.getBatBatch(), RebateDateUtil.format(epochSecond * 1000), tag);
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        saleStockService.saveBatch(cachedDataList);
        log.info("存储数据库成功！");
    }

}
